package com.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heart.common.exception.ValidatorException;
import com.heart.common.utils.*;
import com.heart.dao.entity.Answer;
import com.heart.dao.entity.AnswerDetail;
import com.heart.dao.entity.AnswerMain;
import com.heart.dao.entity.Question;
import com.heart.dao.mapper.AnswerDetailMapper;
import com.heart.dao.mapper.AnswerMainMapper;
import com.heart.dao.mapper.AnswerMapper;
import com.heart.dao.mapper.QuestionMapper;
import com.heart.service.AnswerMainService;
import com.heart.service.QuestionService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@Service
public class AnswerMainServiceImpl extends ServiceImpl<AnswerMainMapper, AnswerMain> implements AnswerMainService {

    @Autowired
    private AnswerMainMapper answerMainMapper;
    @Autowired
    private AnswerMapper answerMapper;
    @Autowired
    private AnswerDetailMapper answerDetailMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Autowired
    private QuestionService questionService;


    public boolean saveAnswer(HttpServletRequest request, HttpServletResponse response, AnswerMain answerMain){
        AssertUtils.notNull(answerMain.getQuestionId(), "问卷ID不能为空");
        AssertUtils.notEmpty(answerMain.getAnswerList(), "答卷不能为空");

        if (!questionService.validateQuestionLimit(request,String.valueOf( answerMain.getQuestionId()))){
            return false;
        }
        answerMain.setMainIp(IPUtils.getIpAddr(request));
        String str = request.getHeader("User-Agent");
        answerMain.setUserAgent(str);

        UserAgent userAgent = UserAgent.parseUserAgentString(str);
        // 获取浏览器对象
        Browser browser = userAgent.getBrowser();
        // 获取操作系统对象
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        // 浏览器名
        answerMain.setBrowserName(browser.getName());
        // 浏览器类型
        answerMain.setBrowserGroup(browser.getGroup().toString());
        answerMain.setBrowserVersion(browser.getVersion(str).toString());
        answerMain.setOperatingSystemGroup(operatingSystem.getGroup().toString());
        answerMain.setOperatingSystemName(operatingSystem.getName());

        Date now = new Date();
        answerMain.setMainTime(now);
        // 这个MainSessionId是前端传回来的
        CookieUtils.setCookie(response, answerMain.getMainSessionId(),
                DateTimeUtils.format(now,DateTimeUtils.DATETIME_FORMAT), -7 * 24 * 60 * 60);//7天过期
        answerMainMapper.insert(answerMain);
        // 更新问卷数量+1
        Question question  = questionMapper.selectById(answerMain.getQuestionId());
        if (ObjectUtils.isNull(question.getQuestionNumber())){
            question.setQuestionNumber(0);
        }
        question.setQuestionNumber(question.getQuestionNumber() + 1);
        questionMapper.updateById(question);

        for(Answer answer : answerMain.getAnswerList()){
            answer.setMainId(answerMain.getMainId());
            answerMapper.insert(answer);
            if(CollectionUtils.isNotEmpty(answer.getAnswerDetailList())){
                for(AnswerDetail detail: answer.getAnswerDetailList()){
                    detail.setAnswerId(answer.getAnswerId());
                    answerDetailMapper.insert(detail);
                }
            }
        }
        return true;
    }


    public List<AnswerMain> getAnswerMainListByQuestionId(String questionId) {
        AssertUtils.notEmpty(questionId, "问卷ID不能为空");

        QueryWrapper<AnswerMain> wrapper = new QueryWrapper<>();
        wrapper.eq("tc_question_id",questionId);
        return answerMainMapper.selectList(wrapper);
    }

    public List<Answer> getAnswerListByAnswerMainId(String mainId) {
        AssertUtils.notEmpty(mainId, "答卷ID不能为空");
        QueryWrapper<Answer> wrapperAnswer = new QueryWrapper<>();
        wrapperAnswer.eq("tc_main_id",mainId);
        List<Answer> answers = answerMapper.selectList(wrapperAnswer);
        if(CollectionUtils.isNotEmpty(answers)){
            answers.forEach(m -> {
                QueryWrapper<AnswerDetail> wrapperAnswerDetail = new QueryWrapper<>();
                wrapperAnswerDetail.eq("tc_answer_id",m.getAnswerId());
                List<AnswerDetail> answerDetails = answerDetailMapper.selectList(wrapperAnswerDetail);
                if(CollectionUtils.isEmpty(answerDetails)){
                    m.setAnswerDetailList(new ArrayList<>());
                } else {
                    m.setAnswerDetailList(answerDetails);
                }
            });
        }
        return answers;
    }

    public boolean deleteAnswer(String detailId){
        AssertUtils.notEmpty(detailId, "答题ID不能为空");
        QueryWrapper<Answer> wrapperAnswer = new QueryWrapper<>();
        wrapperAnswer.eq("tc_detail_id",detailId);
        List<Answer> answers = answerMapper.selectList(wrapperAnswer);
        // 删除明细
        if(CollectionUtils.isNotEmpty(answers)) {
            for(Answer answer : answers){
                QueryWrapper<AnswerDetail> wrapperDetail = new QueryWrapper<>();
                wrapperDetail.eq("tc_answer_id", answer.getAnswerId());
                answerDetailMapper.delete(wrapperDetail);
            }
        }
        // 删除本题答卷
        return  answerMapper.delete(wrapperAnswer) > 0;
    }
}
